package com.zmn.mcc.cas.server;

import com.zmn.common.utils.captcha.GifCaptchaUtil;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.awt.*;
import java.io.ByteArrayOutputStream;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author quanjic
 * @version v1.0
 * @since 2020/6/16 14:27
 **/
@Service
public class RedisCaptchaService implements CaptchaService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public GifCaptcha generateGif() {
        GifCaptchaUtil gifCaptcha = new GifCaptchaUtil(200, 80, new Font("宋体", Font.BOLD, 40), 100);
        String key = UUID.randomUUID().toString();
        redisTemplate.opsForValue().setIfAbsent(redisKey(key), gifCaptcha.getWord(), GifCaptchaUtil.TIMEOUT, TimeUnit.SECONDS);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        gifCaptcha.out(out);
        byte[] ba = out.toByteArray();
        IOUtils.closeQuietly(out);
        return new GifCaptcha(key, gifCaptcha.getWord(), ba);
    }

    /**
     * 校验
     * <p>
     * TODO 验证后没有删除验证码
     *
     * @param key  唯一标识
     * @param code 用户输入验证码
     * @return
     */
    @Override
    public boolean check(String key, String code) {

        if (StringUtils.isEmpty(key)) {
            throw new NullPointerException("null key");
        }
        if (StringUtils.isEmpty(code)) {
            throw new NullPointerException("null code");
        }

        String captchaWord = (String) redisTemplate.opsForValue().get(redisKey(key));
        if (captchaWord == null) {
            return false;
        }
        if (!StringUtils.equalsIgnoreCase(captchaWord, code)) {
            return false;
        }
        return true;
    }

    private String redisKey(String key) {
        return "cas:captcha:" + key;
    }

}
